package com.zhouyangyang.system.util;

/**
 * @PackageName: com.zhouyangyang.system.util
 * @ClassName: JwtUtil
 * @Author: zhouyangyang
 * @Date: 2020/8/9 22:14
 * @Description:
 */

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Signature;
import java.util.Base64;
import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtil {
    /**
     * 有效期为一个小时
     */
    public static final Long JWT_TTL = 3600000L;
    /**
     * 设置秘钥明文为itcast
     */
    public static final String JWT_KEY = "Token";

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMills
     * @return
     */
    public static String creatJWT(String id,String subject,Long ttlMills){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long timeMillis = System.currentTimeMillis();
        Date date = new Date(timeMillis);
        if (ttlMills == null){
            timeMillis = JwtUtil.JWT_TTL;
        }
        long expMill = timeMillis + ttlMills;
        Date expDate = new Date(expMill);
        SecretKey secretKey = generalkey();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)   //设置主题,可以是json字符串
                .setExpiration(expDate) //设置过期时间
                .setIssuer("user") //签发者
                .setIssuedAt(date) //签发时间
                .signWith(signatureAlgorithm, secretKey);//使用HS256对称加密算法签名,第二个参数为秘钥
        return jwtBuilder.compact();
    }

    /**
     * 生成加密后的秘钥
     * @return
     */
    public static SecretKey generalkey() {
        byte[] decode = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey aes = new SecretKeySpec(decode, 0, decode.length, "AES");
        return aes;
    }
    /**
     * 解析
     */
    public static Claims parseJWT(String jwt){
        SecretKey generalkey = generalkey();
        return Jwts.parser()
                .setSigningKey(generalkey)
                .parseClaimsJws(jwt)
                .getBody();

    }
}
